// const BasicAuth = require('basic-auth') // 提取token
const Jwt = require('jsonwebtoken') // 解析 token
const crypto = require('crypto') // 加密
const {
    jwt_config
} = require('../../bin/config')
const secretKey = jwt_config.serect
const expiresIn = jwt_config.expiresIn

const utils = {
    // 颁发token
    uPutToken(uid, auth = 1000) { // scope 权限
        const user = {
            uid,
            auth
        }

        const token = Jwt.sign(user,
            secretKey, {
            expiresIn
        })

        return token
    },

    // 加密
    uMd5(str) {
        str += global.config.jwt_config.serect
        const md5 = crypto.createHash('md5');
        const result = md5.update(str).digest('hex'); //hex表示拿到最终为十六进制
        return result;
    },

    getClientIP(req) {
        let ip = req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
            req.ip ||
            req.connection.remoteAddress || // 判断 connection 的远程 IP
            req.socket.remoteAddress || // 判断后端的 socket 的 IP
            req.connection.socket.remoteAddress || ''
        if (ip) {
            ip = ip.replace('::ffff:', '')
        }
        return ip;
    }
}

module.exports = {
    ...utils
}